package com.example.springsecuritydemo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/")
public class IndexController {
    @GetMapping( "index")
    @PreAuthorize("hasAuthority('INDEX')")
    public Map index() {
        SecurityContext context =  SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal(); // 获取用户信息
        Object credentials = authentication.getCredentials(); // 获取用户凭证信息： 密码 ,不推荐返回密码（不安全）
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String name = authentication.getName();

        HashMap result = new HashMap();
        result.put("principal",principal);
        result.put("username",name);
        //hashMap.put("credentials",credentials); //密码不会返回给前端，不推荐返回给前（不安全）
        result.put("authorities",authorities);



        return result;
    }


    @GetMapping( "hello")
    @PreAuthorize("hasAuthority('HELLO')")
    public  Map hello() {
        HashMap result = new HashMap();
        SecurityContext context =  SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal(); // 获取用户信息
        Object credentials = authentication.getCredentials(); // 获取用户凭证信息： 密码 ,不推荐返回密码（不安全）
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        String name = authentication.getName();
        result.put("hello","hello world");
        result.put("principal",principal);
        result.put("username",name);
        result.put("authorities",authorities);
        return result;
    }
}
